package com.baosight.risk.service.riaa.impl;

import com.baosight.risk.api.riaa.RiquInquiryCompService;
import com.baosight.risk.api.workflow.UpdateHandler;
import com.baosight.risk.base.mapper.BaseMapper;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.utils.ShiroUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.riaa.RiquInquiryCompMapper;
import com.baosight.risk.mapper.riaa.RiquInquiryDetailMapper;
import com.baosight.risk.mapper.xtzy.XtzyUserMapper;
import com.baosight.risk.service.riaa.entity.RiquInquiryComp;
import com.baosight.risk.service.riaa.entity.RiquInquiryDetail;
import com.baosight.risk.service.riaa.vo.RiquInquiryCompVO;
import com.baosight.risk.service.riaa.vo.RiquInquiryDetailVO;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RiquInquiryCompServiceImpl extends BaseServiceImpl<RiquInquiryComp> implements RiquInquiryCompService, UpdateHandler {

    @Autowired
    private RiquInquiryDetailMapper riquInquiryDetailMapper;

    @Autowired
    private RiquInquiryCompMapper riquInquiryCompMapper;

    @Autowired
    private XtzyUserMapper xtzyUserMapper;

    @Override
    public BaseMapper getMapper() {
        return riquInquiryCompMapper;
    }


    @Override
    public List<RiquInquiryComp> selectList(RiquInquiryComp inquiryComp) {
        if (StringUtils.isNotEmpty(inquiryComp.getAcctYear())) {
            if (inquiryComp.getAcctYear().length() > 4) {
                inquiryComp.setAcctYear(inquiryComp.getAcctYear().substring(0, 4));
            }
        }
        servicePage();
        List<RiquInquiryComp> list = riquInquiryCompMapper.selectList(inquiryComp);
        // flag 表示从分配页面查询,
        if ("flag".equals(inquiryComp.getExt1())) {
            if (ShiroUtils.getUser().isAdmin()) {
                // 判断是否admin,过滤父节点为0的数据
                list = list.stream().filter(o -> "0".equals(o.getParentGuid())).collect(Collectors.toList());
            } else {
                // 过滤父节点为0的数据并且当前登录人所属单位
                list = list.stream().filter(o -> ShiroUtils.getUser().getExt1().equals(o.getSubmitCompCode()))
                        .filter(o -> "0".equals(o.getParentGuid())).collect(Collectors.toList());
            }
        }
        return list;
    }


    @Override
    public List<RiquInquiryComp> getByIds(List<String> ids) {
        return riquInquiryCompMapper.getByIds(ids);
    }

    @Override
    public RiquInquiryCompVO getById(String id) {
        RiquInquiryCompVO compVO = new RiquInquiryCompVO();
        RiquInquiryComp comp = riquInquiryCompMapper.selectByPrimaryKey(id);
        BeanUtils.copyBeanProp(compVO, comp);
        //找到总部的详细
        compVO.setRiquInquiryBGTADetail(riquInquiryDetailMapper.selectDetalByBGTACompId(id,comp.getSendCompCode()));

        //找到其他部门的详细
        compVO.setRiquInquiryDetail(riquInquiryDetailMapper.selectDetalByCompId(id));
        return compVO;
    }

    @Override
    public List<RiquInquiryDetailVO> quesAnalysis(String quId) {
        List<RiquInquiryDetailVO>  list = Lists.newArrayList();
        //list = riquInquiryDetailMapper.quesAnalysis(quId);
        list = riquInquiryDetailMapper.quesAnalysisGroupByQuesNo(quId);
        for (RiquInquiryDetailVO detailVO : list) {
//            if (!"1".equals(detailVO.getCreateFlag())) {
//                detailVO.setCreateBy(null);
//            }
            if (StringUtils.isNotEmpty(detailVO.getCreateBy())){
                XtzyUser user = xtzyUserMapper.selectByName(detailVO.getCreateBy());
                if(user !=null){
                    detailVO.setCreateBy(user.getUserDesc());
                } else {
                    detailVO.setCreateBy(null);
                }
            }
        }
        return list;
    }



    @Override
    public List<RiquInquiryComp> queryInquiryInfo(RiquInquiryComp inquiryComp) {
        if (StringUtils.isNotEmpty(inquiryComp.getAcctYear())) {
            if (inquiryComp.getAcctYear().length() > 4) {
                inquiryComp.setAcctYear(inquiryComp.getAcctYear().substring(0, 4));
            }
        }
        servicePage();
        List<RiquInquiryComp> list = riquInquiryCompMapper.selectList(inquiryComp);
        return list;
    }

    @Override
    public RiquInquiryCompVO saveInquiry(RiquInquiryCompVO compVO, XtzyUser user) {
        if (CollectionUtils.isNotEmpty(compVO.getRiquInquiryDetail())) {
            //后新增
            for (RiquInquiryDetail detail : compVO.getRiquInquiryDetail()) {
                saveDetail(detail, compVO.getId(), user);
            }
        }
        if (CollectionUtils.isNotEmpty(compVO.getRiquInquiryBGTADetail())) {
            for (RiquInquiryDetail detail : compVO.getRiquInquiryBGTADetail()) {
                saveDetail(detail, compVO.getId(), user);
            }
        }
        return compVO;
    }

    public void saveDetail(RiquInquiryDetail detail, String compId, XtzyUser user) {
        if (StringUtils.isEmpty(detail.getId())) {
//            detail.setDutyCompCode(user.getExt1());
//            detail.setDutyCompName(user.getExt2());
            detail.setQuResultId(compId);
            detail.setCreateFlag("1");//新增数据
            detail.setFieldCode("QT");
            detail.setFieldName("其他风险");
            int rowOrder;
            Integer i = riquInquiryDetailMapper.queryMaxRowOrder(compId);
            if(i == null){
                rowOrder = 1;
            } else {
                rowOrder = i + 1;
            }
            detail.setRowOrder(rowOrder);
            //新增
            detail = (RiquInquiryDetail) BeanUtils.initBean(detail);
            riquInquiryDetailMapper.insert(detail);
        } else {
            detail = (RiquInquiryDetail) BeanUtils.updateBean(detail);
            riquInquiryDetailMapper.updateByPrimaryKeySelective(detail);
        }
    }

    @Override
    public Integer deleteDetailById(String id) throws Exception {
        RiquInquiryDetail detail = riquInquiryDetailMapper.selectByPrimaryKey(id);
        if (null != detail) {
            return riquInquiryDetailMapper.deleteByPrimaryKey(id);
        } else {
            throw new Exception("数据不存在");
        }

    }


    @Override
    public Integer saveSubmit(RiquInquiryCompVO compVO, XtzyUser user) {
        compVO.setSubmitUserCode(user.getUserCode());
        compVO.setSubmitUserName(user.getUserDesc());
        this.saveInquiry(compVO, user);
        compVO.setStatus("A02");
        compVO.setStatusName("已提交");
        return riquInquiryCompMapper.updateByPrimaryKey(compVO);
    }

    public void updateInquiryComp(String id){
        RiquInquiryComp inquiryComp = get(id);
        if(StringUtils.isNotEmpty(inquiryComp.getParentGuid())){
            RiquInquiryComp riquInquiryComp = new RiquInquiryComp();
            riquInquiryComp.setParentGuid(inquiryComp.getParentGuid());
            List<RiquInquiryComp> list = riquInquiryCompMapper.selectList(riquInquiryComp);
            if (CollectionUtils.isNotEmpty(list)) {
                for (RiquInquiryComp comp : list) {
                    if(!"A09".equals(comp.getStatus())){
                        return;
                    }
                }
            }
            RiquInquiryComp comp = new RiquInquiryComp();
            comp.setId(inquiryComp.getParentGuid());
            comp.setStatus("A09");
            comp.setStatusName("已提交");
            update(comp);
        }

    }


    /**
     * status	当前节点状态
     * nextStatus	下一节点状态
     * nextStatusName	下一节点状态名称
     * acctYear	当前年度
     * quarterCurrent	当前季度
     * deptCode	填报人的部门编码
     * bizGuid 业务id
     *
     * @param params
     */
    @Override
    public boolean updateStatus(Map<String, Object> params) {
        RiquInquiryComp inquiryComp = new RiquInquiryComp();
        inquiryComp.setId((String) params.get("bizGuid"));
        inquiryComp.setStatus((String) params.get("nextStatus"));
        inquiryComp.setStatusName((String) params.get("nextStatusName"));
        if ("A01".equals(params.get("status"))) {
            XtzyUser user = getUser();
            inquiryComp.setSubmitUserCode(user.getUserCode());
            inquiryComp.setSubmitUserName(user.getUserDesc());
        }
        update(inquiryComp);
        updateInquiryComp((String) params.get("bizGuid"));
        return true;
    }
}
